import 'package:acgn_pioneer/models/base_model.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../public.dart';

class WithdrawalPage extends StatefulWidget {
  WithdrawalPage({Key key}) : super(key: key);
  @override
  _WithdrawalPageState createState() => _WithdrawalPageState();
}

class _WithdrawalPageState extends State<WithdrawalPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController = RefreshController();
  bool isInitLoaded = false;
  Map<String, dynamic> userWithdraw = {
    'pager': PagerModel.fromJson({}),
    'data': []
  };
  List withdrawdetailType = ['', '次元账户', '支付宝', '银行卡'];
  List withdrawdetailStatus = ['', '发起申请', '审核中', '成功', '失败'];
  @override
  void initState() {
    super.initState();
    requestHanddle();
  }

  Future requestHanddle() async {
    int page = userWithdraw['pager'].page + 1;
    return Future.delayed(Duration(milliseconds: 3), () {
      return UserService.getUserWithdrawdetail(
          {'page': page, 'size': userWithdraw['pager'].size}).then((res) {
        userWithdraw['data'].addAll(res.data);
        // 修复服务端返回page为总页数，这里我们需要的是当前页码
        res.pager.page = page;
        if (res.pager.total <= page * res.pager.size) {
          _refreshController.loadNoData();
        } else {
          userWithdraw['pager'] = res.pager;
          _refreshController.loadComplete();
        }
        isInitLoaded = true;
        setState(() {});
        return res;
      }).catchError((err) {
        isInitLoaded = true;
        _refreshController.loadFailed();
        setState(() {});
      });
    });
  }

  getWithdrawdetailStatus(status) {
    // ['', '发起申请', '审核中', '成功', '失败']
    String str = '提现';
    switch (status) {
      case 1:
      case 2:
        str = '正在';
        break;
      default:
        break;
    }
    return str + withdrawdetailStatus[status];
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    int len = userWithdraw['data'].length;
    return RefreshConfig(
        child: SmartRefresher(
            enablePullDown: false,
            enablePullUp: isInitLoaded && len > 0,
            controller: _refreshController,
            onLoading: requestHanddle,
            onRefresh: () async {
              await requestHanddle();
              _refreshController.refreshCompleted();
            },
            child: isInitLoaded
                ? (len > 0
                    ? ListView.builder(
                        shrinkWrap: true,
                        itemCount: len,
                        itemBuilder: (BuildContext context, index) {
                          return _getItem(userWithdraw['data'][index]);
                        })
                    : EmptyComponent())
                : LoadingComponent()));
  }

  Widget _getItem(item) {
    return Container(
        padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
        child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                    Text('提现到${withdrawdetailType[item.withdrawWay]}',
                        style: TextStyle(
                            fontSize: 14, height: 1.75, color: Colors.white)),
                    Text(
                        '申请时间: ${StringUtil.formatDate(item.createdTime, 'yyyy.MM.dd hh:mm:ss')}',
                        style: TextStyle(
                            fontSize: 12,
                            height: 1.5,
                            color: ColorUtil.rgba(255, 255, 255, 0.6))),
                    Text(
                        '到账时间: ${StringUtil.formatDate(item.updatedTime, 'yyyy.MM.dd hh:mm:ss')}',
                        style: TextStyle(
                            fontSize: 12,
                            color: ColorUtil.rgba(255, 255, 255, 0.6)))
                  ])),
              Container(
                child: Column(children: [
                  Text(
                    '￥${item.cashRMB}',
                    style: TextStyle(fontSize: 16, color: Colors.yellow),
                  ),
                  Text(
                    getWithdrawdetailStatus(item.status),
                    style: TextStyle(
                        fontSize: 12,
                        height: 1.5,
                        color: ColorUtil.rgba(255, 255, 255, 0.6)),
                  )
                ]),
              )
            ]));
  }

  @override
  bool get wantKeepAlive => true;
}
